<template>
  <div class="user-settings-container">
    <h2>AI 配置设置</h2>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>AI 服务提供商配置</span>
          <el-button type="primary" @click="saveSettings">保存设置</el-button>
        </div>
      </template>
      
      <el-form :model="settings" label-width="120px" v-loading="loading">
        <el-form-item label="AI 提供商">
          <el-select v-model="settings.preferred_ai_provider" placeholder="选择AI服务提供商" style="width: 100%">
            <el-option 
              v-for="(provider, key) in aiProviders" 
              :key="key"
              :label="provider.name" 
              :value="key" 
            />
          </el-select>
        </el-form-item>
        
        <el-divider content-position="left">OpenAI 配置</el-divider>
        <el-form-item label="OpenAI API Key">
          <el-input 
            v-model="settings.openai_api_key" 
            placeholder="输入OpenAI API Key" 
            show-password
          />
          <div class="key-info" v-if="settings.openai_api_key">
            已设置 API Key: {{ settings.openai_api_key }}
          </div>
        </el-form-item>
        
        <el-divider content-position="left">DeepSeek 配置</el-divider>
        <el-form-item label="DeepSeek API Key">
          <el-input 
            v-model="settings.deepseek_api_key" 
            placeholder="输入DeepSeek API Key" 
            show-password
          />
          <div class="key-info" v-if="settings.deepseek_api_key">
            已设置 API Key: {{ settings.deepseek_api_key }}
          </div>
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="success" 
            @click="validateKey(settings.preferred_ai_provider)"
            :disabled="isValidateDisabled"
          >
            验证 API Key
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="box-card settings-info">
      <template #header>
        <div class="card-header">
          <span>AI 服务说明</span>
        </div>
      </template>
      <div class="info-content">
        <h3>AI 任务拆分功能</h3>
        <p>系统使用 AI 自动将大型任务分解为可管理的子任务。您可以选择使用以下 AI 服务提供商：</p>
        
        <h4>OpenAI</h4>
        <p>使用 OpenAI 的 GPT 模型进行任务拆分。适合通用的任务拆分场景，需要 OpenAI API Key。</p>
        
        <h4>DeepSeek</h4>
        <p>使用 DeepSeek 的大语言模型进行任务拆分。非常适合技术和代码相关的任务拆分，需要 DeepSeek API Key。</p>
        
        <p>请注意：所有 API Key 信息仅存储在您的账户中，不会被共享。</p>
      </div>
    </el-card>
  </div>
</template>

<script>
import { reactive, ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

export default {
  name: 'UserSettings',
  setup() {
    const loading = ref(false)
    const settings = reactive({
      username: 'admin',
      preferred_ai_provider: 'openai',
      openai_api_key: '',
      deepseek_api_key: ''
    })
    const aiProviders = ref({})
    
    const isValidateDisabled = computed(() => {
      if (settings.preferred_ai_provider === 'openai' && !settings.openai_api_key) {
        return true
      }
      if (settings.preferred_ai_provider === 'deepseek' && !settings.deepseek_api_key) {
        return true
      }
      return false
    })
    
    const getSettings = async () => {
      loading.value = true
      try {
        const response = await axios.get('/api/user/settings')
        if (response.data.status === 'success') {
          const data = response.data.data
          settings.username = data.username
          settings.preferred_ai_provider = data.preferred_ai_provider
          settings.openai_api_key = data.openai_api_key
          settings.deepseek_api_key = data.deepseek_api_key
          aiProviders.value = data.ai_providers
        }
      } catch (error) {
        console.error('获取设置失败:', error)
        ElMessage.error('获取用户设置失败')
      } finally {
        loading.value = false
      }
    }
    
    const saveSettings = async () => {
      loading.value = true
      try {
        const response = await axios.post('/api/user/settings', settings)
        if (response.data.status === 'success') {
          ElMessage.success('设置保存成功')
        } else {
          ElMessage.error(response.data.message || '保存设置失败')
        }
      } catch (error) {
        console.error('保存设置失败:', error)
        ElMessage.error('保存用户设置失败')
      } finally {
        loading.value = false
      }
    }
    
    const validateKey = async (provider) => {
      loading.value = true
      let apiKey = ''
      
      if (provider === 'openai') {
        apiKey = settings.openai_api_key
      } else if (provider === 'deepseek') {
        apiKey = settings.deepseek_api_key
      }
      
      if (!apiKey) {
        ElMessage.warning(`请先设置 ${provider} 的 API Key`)
        loading.value = false
        return
      }
      
      try {
        const response = await axios.post('/api/user/validate-api-key', {
          provider,
          api_key: apiKey
        })
        
        if (response.data.status === 'success' && response.data.is_valid) {
          ElMessage.success(`${provider} API Key 验证成功`)
        } else {
          ElMessage.error(response.data.message || `${provider} API Key 验证失败`)
        }
      } catch (error) {
        console.error('验证API Key失败:', error)
        ElMessage.error(`验证 ${provider} API Key 失败`)
      } finally {
        loading.value = false
      }
    }
    
    onMounted(() => {
      getSettings()
    })
    
    return {
      loading,
      settings,
      aiProviders,
      isValidateDisabled,
      saveSettings,
      validateKey
    }
  }
}
</script>

<style scoped>
.user-settings-container {
  padding: 20px;
  max-width: 900px;
  margin: 0 auto;
}

h2 {
  margin-bottom: 20px;
  color: #303133;
}

.box-card {
  margin-bottom: 30px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.key-info {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
}

.settings-info {
  background-color: #f9fafc;
}

.info-content {
  color: #606266;
}

.info-content h3 {
  margin-top: 0;
  color: #303133;
}

.info-content h4 {
  margin-top: 15px;
  margin-bottom: 5px;
  color: #303133;
}

.info-content p {
  margin-bottom: 10px;
  line-height: 1.6;
}

.el-divider {
  margin: 24px 0;
}
</style> 